package com.fatcat.easybuy.config;


import com.fatcat.easybuy.listener.OrderExpireListener;
import com.fatcat.easybuy.service.EasyBuyOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

@Configuration
public class RedisConfig {

    private final RedisConnectionFactory redisConnectionFactory;

    @Autowired
    public RedisConfig(RedisConnectionFactory redisConnectionFactory) {
        this.redisConnectionFactory = redisConnectionFactory;
    }

    /**
     * Redis消息监听容器：管理监听线程和事件分发
     */
    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer() {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(redisConnectionFactory);
        // 只监听 "order:" 前缀的过期键
        container.addMessageListener(orderExpireListener(container), new PatternTopic("__keyevent@*__:expired"));
        return container;
    }

    /**
     * 订单过期监听器
     */
    @Bean
    public OrderExpireListener orderExpireListener(RedisMessageListenerContainer container) {
        // 传入容器，让监听器继承父类的事件处理能力
        return new OrderExpireListener(container);
    }
}